﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zj.OpenAuth.Domain.Core;
using Zj.OpenAuth.Domain.Interface;
using Zj.OpenAuth.DTO.Common;

namespace Zj.OpenAuth.Repository
{
    /// <summary>
    /// role repository service
    /// </summary>
    public class RoleRepository : BaseRepository<Role>, IRoleRepository
    {
        public RoleRepository(DbContext ctx)
            : base(ctx)
        {

        }


        /// <summary>
        /// get all menu list by role
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<int> GetAllMenuListByRole(int roleId)
        {
            var roleMenus = Context.Set<RoleMenuMapping>().Where(rm => rm.RoleId == roleId);
            return roleMenus.Select(rm => rm.MenuId).ToList();
        }



        /// <summary>
        /// get all menu list by role
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<int> GetAllRoleListByUser(int userId)
        {
            var roleMenus = Context.Set<UserRoleMapping>().Where(rm => rm.UserId == userId);
            return roleMenus.Select(rm => rm.RoleId).ToList();
        }



        /// <summary>
        /// update role menu mapping
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="roleMenus"></param>
        /// <returns></returns>
        public bool UpdateRoleMenu(int roleId, List<RoleMenuMapping> roleMenus)
        {
            var rms = Context.Set<RoleMenuMapping>().Where(rm => rm.RoleId == roleId);
            foreach (var item in rms)
            {
                Context.Set<RoleMenuMapping>().Remove(item);
            }

            Context.Set<RoleMenuMapping>().AddRange(roleMenus);
            return Context.SaveChanges()>0;
        }
    }
}
